﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PDX.ChangeTracking;

namespace PdxDemo.MasterDetailDemo
{
    public class CustomChangeManager : PDX.ChangeTracking.AbstractChangeManager<DecoratedChange>
    {
        public ViewModel Viewmodel { get; set; }

        public CustomChangeManager(ViewModel vm)
        {
            Viewmodel = vm;
        }

        protected override DecoratedChange CreateCustomSnapshotAndCaptureCustomProperties(Snapshot snap)
        {
            var customSnap = new DecoratedChange();
            customSnap.SelectedMaster = Viewmodel.SelectedMaster;
            customSnap.SelectedApprentice = Viewmodel.SelectedApprentice;
            return customSnap;
        }

        protected override bool IsContinuation(DecoratedChange current, DecoratedChange previous)
        {
            if (current.SelectedApprentice != previous.SelectedApprentice ||
                current.SelectedMaster != previous.SelectedMaster)
            {
                return false;
            }

            return base.IsContinuation(current, previous);
        }

        protected override void UndoChange(Change<DecoratedChange> change)
        {
            Viewmodel.SelectedMaster = change.OriginalSnapshot.SelectedMaster;
            Viewmodel.SelectedApprentice = change.OriginalSnapshot.SelectedApprentice;

            base.UndoChange(change);
        }

        protected override void RedoChange(Change<DecoratedChange> change)
        {
            Viewmodel.SelectedMaster = change.LatestSnapshot.SelectedMaster;
            Viewmodel.SelectedApprentice = change.LatestSnapshot.SelectedApprentice;

            base.RedoChange(change);
        }

        public override void  UpdateDescription(Change<DecoratedChange> change)
        {
            change.Description = string.Format("{3}'s {0}: from '{1}' to '{2}'",
                change.OriginalSnapshot.PropertyModel.DisplayName,
                change.OriginalSnapshot.Value,
                change.LatestSnapshot.Value,
                change.OriginalSnapshot.SelectedApprentice.Name);
        }
    }

    public class DecoratedChange : PDX.ChangeTracking.Snapshot
    {
        public MasterPOCO SelectedMaster { get; set; }
        public ApprenticePOCO SelectedApprentice { get; set; }
    }
}
